package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不符合 返回
            return Result.fail("手机号格式错误");
        }

        //3.符合 生成验证码
        String code = RandomUtil.randomNumbers(6);

        //4.保存验证码到redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //5.发验证码
        log.debug("发送验证码成功，验证码：{}",code);

        //6.返回ok
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号（防止获取验证码后修改手机号）
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)) {
            //不符合 返回
            return Result.fail("手机号格式错误");
        }

        //2，校验验证码,从redis获取
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        String code = loginForm.getCode();

        if(cacheCode == null || !cacheCode.equals(code)){
            //3.不一致，报错
            return Result.fail("验证码错误");
        }

        //4.根据手机号查询用户 query等于select * from tb_user
        User user = query().eq("phone", phone).one();

        //5.判断用户是否存在
        if(user == null){
            //6.不存在 创建
            user = createUserWithPhone(phone);
        }

        //7.保存用户信息至redis
        //7.1生成token作为用户登录令牌
        String token = UUID.randomUUID().toString(true);

        //7.2将user对象以hash存储至redis
        UserDTO userDTO = BeanUtil.copyProperties(user,UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token,userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY + token,LOGIN_USER_TTL,TimeUnit.SECONDS);

        //7.3token返回给客户端
        return Result.ok(token);
    }

    @Override
    public Result sign() {
        //1.获取当前用户和日期
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();

        //1.1.日期格式转换,获取key后缀
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));

        String key = USER_SIGN_KEY + userId + keySuffix;

        //2.保存签到信息至redis
        int day = now.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, day - 1, true);

        return Result.ok();
    }

    /**
     * 计算连续签到天数
     * @return
     */
    @Override
    public Result signCount() {
        //1.获取本月至今所有签到记录
        //1.1.获取当前用户和日期
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        //1.2.日期格式转换,获取key后缀
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        //1.3.获取第几天
        int day = now.getDayOfMonth();

        //2.查询数据库，获得签到记录，返回十进制数
        List<Long> result = stringRedisTemplate.opsForValue().bitField(
                key,
                BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(day)).valueAt(0));  //去符号位：unsigned，偏移量：valueAt

        if(result == null || result.isEmpty())
            return Result.ok(0);

        //2.1.获取二进制数（只执行一次get，list中仅有一条数据）
        Long num = result.get(0);

        if(num == null || num == 0)
            return Result.ok(0);

        //3.循环遍历，每一位分别与1分别做与运算
        int count = 0;

        while (true){

            if ((num & 1) == 0) {
                //3.1.未签到，为0
                break;
            }else {
                //3.2.签到，为1
                count ++ ;
                //右移一位
                num >>>= 1;
            }

        }

        return Result.ok(count);
    }

    private User createUserWithPhone(String phone){
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));

        //用mybatis-plus保存
        save(user);
        return user;
    }

}
